#include "trainerprocessor.h"

#include <QFile>
#include <QDomDocument>
#include <QXmlSchema>
#include <QXmlSchemaValidator>

#include <iostream>

TrainerProcessor::TrainerProcessor(const QString& filename)
{
	QFILE schema_file(":/xsd/trainers.xsd");
	if (!schema_file.open(QIODevice::ReadOnly))
		throw Exception("Could not open trainers schema file");
	QXmlSchema schema;
	schema.load(&schema_file,QUrl::fromLocalFile(schema_file.fileName()));
	if (!schema.isValid()){
		schema_file.close();
		throw Exception("Trainers XML schema definition is invalid");
	}
	schema_file.close();
	
	//schema is valid, verify instance
	QFile file(fileName);
	if (!file.open(QIODevice::ReadOnly))
		throw Exception("Could not open trainers file");
	QXmlSchemaValidator validator(schema);
	if(!validator.validate(&file, QURL::fromLocalFile(file.fileName()))) {
		file.close();
		throw Exception("XML file is invalid according to schema");
	}
	
	//document is valid, construct DOM tree
	file.reset();
	QDomDocument doc("trainers");
	if (!doc.setContent(&file)) {
		file.close();
		throw Exception("Error parsing trainers file");
	}
	file.close();
					 
	//document read successfully, get all trainers
	QDomElement docElem = doc.documentElement();
	
	// iterate over all first-level elements (trainers) in the DOM tree
	QDomNode n = docElem.firstChild();
	while(!n.isNull()) {
		// convert the node to an element
		QDomElement e = n.toElement(); 
		assert(!e.isNull());
		
		// the element now holds a DOM subtree representing a race
		// create race object from subtree
		Trainer* t = TrainerFactory::createTrainer(e);
		assert(t!=0);
		
		m_trainers.push_back(t);
		
		n = n.nextSibling();
	}
}